package com.example.abc.service;

import com.example.abc.dto.MyUserDetails;
import com.example.abc.entity.Account;
import com.example.abc.entity.UserAuthority;
import com.example.abc.repository.AccountDao;
import com.example.abc.web.IndexController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Peter on 2018/4/25.
 */
@Service
public class DatabaseUserDetailService implements UserDetailsService {
    public static final Logger logger = LoggerFactory.getLogger(DatabaseUserDetailService.class);
    @Autowired
    private AccountService accountService;

    @Autowired
    private UserAuthorityService userAuthorityService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库查询用户信息
        Account account = accountService.findByUsername(username);
        if (account == null) {
            logger.warn("用户不存在,username=" + username);
            throw new UsernameNotFoundException("用户不存在");
        }
        // 查询权限
        List<UserAuthority> userAuthorities = userAuthorityService.findByUid(account.getUid());
        MyUserDetails user = new MyUserDetails();
        user.setAuthorities(userAuthorities);
        user.setAvatar_url(account.getAvatar_url());
        user.setEnabled(account.getEnabled());
        user.setPassword(account.getPassword());
        user.setUid(account.getUid());
        user.setUsername(account.getUsername());
        return user;
    }

    public static void main(String[] args) {
        System.out.println(new BCryptPasswordEncoder().encode("user"));
    }
}
